/**
 * 
 */
package org.dragonfire.dasm.preprocessor.blockDefs;

import org.dragonfire.dasm.Command;
import org.dragonfire.dasm.preprocessor.Block;
import org.dragonfire.dasm.preprocessor.BlockDef;
import org.dragonfire.dasm.preprocessor.Preprocessor;

/**
 * @author Darth Android
 */
public class SwitchBlockDef extends BlockDef {

	/**
	 * @author Darth Android
	 */
	public class SwitchBlock extends Block {

		private String variable;
		private boolean used = false;

		public SwitchBlock(String variable) {
			super("switch", "endswitch", new String[] {
					"case", "break"
			});
			setName("switch");
			this.variable = variable;
		}

		@Override
		public void parsePersonalDirective(Preprocessor prep, Command c) {
			String name = c.getName();
			if (name.equalsIgnoreCase("break") || name.equalsIgnoreCase("switch"))
				prep.setParsing(false);
			else if (name.equalsIgnoreCase("case") && !used) {
				used = true;
				String var2 = c.getParam(0);
				if (prep.getCompiler().evalBool("(" + variable + ")===(" + var2 + ")"))
					prep.setParsing(true);
			}
			else if (name.equalsIgnoreCase("default") && !used) {
				prep.setParsing(true);
				used = true;
			}
			else
				super.parsePersonalDirective(prep, c);
		}
	}

	@Override
	public Block createBlock(Preprocessor prep, Command c) {
		SwitchBlock sb = new SwitchBlock(c.getParam(0));
		return sb;
	}
}
